<?php
class Region_model extends BZ_Model
{
    protected $table = 'region';
    
    public function find()
    {
        return $this->db->get($this->table);
    }
    
    public function findById($id)
    {
        $this->db->where('region_id', $id);
        return $this->db->get($this->table);
    }
    
    public function findByAutocomplete($region_type)
    {
        $this->db->select('region_name, region_pinyin, region_abbr');
        $this->db->where('region_type', $region_type);
        return $this->db->get($this->table);
    }
    
    function children_of($parent_id)
    {
        $this->db->where('parent_id', (int)$parent_id);
        $result = $this->db->get($this->table);
        if ($result->num_rows() > 0){
            return $result->result_array();
        }
        return array();
    }
    function all_region()
    {
        $result = $this->db->get($this->table);
        if ($result->num_rows() > 0){
            return $result->result_array();
        }
        return array();
    }

    public function getNewRegion()
    {
        $result = $this->db->get($this->table);
        $rows = array();
        foreach ($result->result_array() as $row) {
            $rows[$row['region_id']] = $row;
        }
        return $rows;
    }
    
    public function getRegionNames($params)
    {
        $this->db->select('region_name');
        $this->db->where_in('region_id', $params);
        $this->db->order_by('region_id', 'ASC'); //省市区顺序
        $res = $this->db->get($this->table);
        $regionName = [];
        if ($res->num_rows() > 0) {
            foreach($res->result_array() as $key => $item) {
                $regionName[$key] = $item->region_name;
            }
        }
        if (!empty($regionName)) {
            return implode(' ', $regionName);
        }
        return '';
    }

    public function findByParentId($parentId)
    {
        $this->db->select('region_id, region_name, region_type');
        $this->db->from($this->table);
        $this->db->where('parent_id', $parentId);
        return $this->db->get();
    }

    public function updateRegionCode($data)
    {
        $this->db->update_batch($this->table, $data, 'region_id');
    }
    
    public function getByRegionIds($regionids=array())
    {
        $this->db->where_in('region_id', $regionids);
        $this->db->order_by('region_id', 'ASC');
        return $this->db->get($this->table);
    }

}